#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>

 struct ListNode {
	int val;
	ListNode *next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode *next) : val(x), next(next) {}
	
};

class Solution {
public:
	ListNode* removeNthFromEnd(ListNode* head, int n)
	{
		if (head->next == nullptr&&n == 1)
		{
			//delete head;
			head = nullptr;
			return head;
		}
		ListNode* l = head, *mid = head, *r = head;
		int count = n - 1;
		while (count--)
		{
			r = r->next;
		}

		while (r->next)
		{
			mid = mid->next;
			r = r->next;
		}

		if (mid == head)
		{
			head = mid->next;
			return head;
		}
		while (l->next != mid)
			l = l->next;
		//delete mid;
		l->next = mid->next;
		return head;
	}
};